package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"testGin/model/mysql"
	"testGin/model/tool"
)

type AppiController struct{
	api mysql.ApiNode
}

func (ctr AppiController) Index(c *gin.Context) {
	c.HTML(200, "system/appi/index.html", gin.H{})
}
func (ctr AppiController) GetList(c *gin.Context) {
	nodes := []mysql.ApiNode{}
	db := mysql.Db
	db.Find(&nodes).Order("level asc").Order("px asc")
	tool.Success(c, 200, "成功", nodes)
}

func (ctr AppiController) Add(c *gin.Context) {

	nodes, _ := ctr.api.GetPidMenuList()

	c.HTML(200, "system/appi/add.html", nodes)
}

func (ctr AppiController) AddAjax(c *gin.Context) {

	if err := c.Bind(&ctr.api); err != nil {
		tool.Error(c, 0, err.Error())
		return
	}
	errs := ctr.api.Add(ctr.api)
	if errs != nil {
		tool.Error(c, 0, errs.Error())
		return
	}
	tool.Success(c, 200, "添加成功", "")
}

func (ctr AppiController) Edit(c *gin.Context) {

	id := c.DefaultQuery("id", "0")

	if ids, _ := strconv.Atoi(id); ids < 0 {
		tool.Error(c, 0, "id不正确")
		return
	} else {
		fmt.Println("ids", ids)
		node, _ := ctr.api.GetItemById(ids)
		nodes, _ := ctr.api.GetPidMenuList()

		c.HTML(200, "system/appi/edit.html", gin.H{
			"list": nodes,
			"item": node,
		})
	}
}

func (ctr AppiController) EditAjax(c *gin.Context) {


	if err := c.Bind(&ctr.api); err != nil {
		tool.Error(c, 0, err.Error())
		return
	}

	errs := mysql.ApiNode{}.Save(ctr.api)

	if errs != nil {
		tool.Error(c, 0, errs.Error())
		return
	}
	tool.Success(c, 200, "修改成功", "")
}
func (ctr AppiController) Del(c *gin.Context) {

	id := c.DefaultQuery("id", "0")
	if ids, _ := strconv.Atoi(id); ids < 0 {
		tool.Error(c, 0, "id参数错误")
		return
	} else {

		errs := ctr.api.Del(ids)
		if errs != nil {
			tool.Error(c, 0, errs.Error())
			return
		}
		tool.Success(c, 200, "删除成功", "")
	}

}
func (ctr AppiController) Status(c *gin.Context) {
	id := c.DefaultQuery("id", "0")
	status := c.DefaultQuery("status", "0")

	ids, err := strconv.Atoi(id)
	if  ids < 0 {
    	tool.Error(c,0,err.Error())
    	return
	}

	statuss, err := strconv.Atoi(status);
	if  statuss < 0 {
		tool.Error(c,0,err.Error())
		return
	}

	errs := ctr.api.SetStatus(ids,statuss)

	if errs != nil{
		tool.Error(c,0,errs.Error())
		return
	}

	tool.Success(c,200,"操作成功","")

}
func (ctr AppiController) Px(c *gin.Context) {

	id := c.DefaultQuery("id", "0")
	px := c.DefaultQuery("px", "0")

	ids, err := strconv.Atoi(id)
	if  ids < 0 {
		tool.Error(c,0,err.Error())
		return
	}

	pxs, err := strconv.Atoi(px);
	if  pxs < 0 {
		tool.Error(c,0,err.Error())
		return
	}

	errs := ctr.api.Sort(ids,pxs)

	if errs != nil{
		tool.Error(c,0,errs.Error())
		return
	}

	tool.Success(c,200,"操作成功","")
}
